package com.lenovo.manufacture.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.lenovo.manufacture.BaseActivity;
import com.lenovo.manufacture.R;
import com.lenovo.manufacture.utils.HttpTools;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import androidx.annotation.RequiresApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class T7 extends BaseActivity {

    private ImageView carMonView;


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_t7);
        super.createToolBar("生产过程监控");
        carMonView = findViewById(R.id.carMonView);
        initWebView();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @SuppressLint({"SetJavaScriptEnabled"})
    private void initWebView() {

        TWebView webView = new TWebView(this, null);
        ViewGroup viewParent = findViewById(R.id.webView1);
        viewParent.addView(webView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT));

        webView.loadUrl("file:///android_asset/carMon.html");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                /* mWebView.showLog("test Log"); */
            }
        });

        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                webView.loadUrl("javascript:changeStep(7)");
            }
        });


        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.setBackgroundColor(0);
        webView.requestFocus();
        webView.setInitialScale(25);
//        webView.addJavascriptInterface(new T7.JavaScriptInterface(this), "nativeMethod");
        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSetting.setSupportZoom(true);
//        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
//        webSetting.setAppCacheEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setDefaultTextEncodingName("utf-8");
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);

        new reloadWebView(this, 5, webView).run();
    }

    protected class reloadWebView extends TimerTask {
        Activity context;
        Timer timer;
        WebView wv;

        public reloadWebView(Activity context, int seconds, WebView wv) {
            this.context = context;
            this.wv = wv;

            timer = new Timer();
            /* execute the first task after seconds */
            timer.schedule(this,
                    seconds * 1000,  // initial delay
                    seconds * 1000); // subsequent rate

        }

        @Override
        public void run() {
            if (context == null || context.isFinishing()) {
                // Activity killed
                this.cancel();
                return;
            }

            ((Runnable) () -> {
                // 先查询 UserProductionLine 获取 position == 2
                String upl = "";

                HttpTools.url("/UserProductionLine/search")
                        .postAsy(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                int UPL = -1;
                                Map map = new Gson().fromJson(response.body().string(), Map.class);
                                ArrayList data = (ArrayList) map.get("data");
                                for (Object datum : data) {
                                    LinkedTreeMap datum1 = (LinkedTreeMap) datum;
                                    if ((Double) datum1.get("position") == 2) {
                                        UPL = Double.valueOf((Double) datum1.get("stageId")).intValue();
                                    }
                                }
                                if (UPL != -1) {
                                    HttpTools.url("/PLStep/search")
                                            .addParam("id", String.valueOf(UPL)).postAsy(new Callback() {
                                        @Override
                                        public void onFailure(Call call, IOException e) {

                                        }

                                        @Override
                                        public void onResponse(Call call, Response response) throws IOException {
                                            Map map = new Gson().fromJson(response.body().string(), Map.class);
                                            ArrayList data = (ArrayList) map.get("data");
                                            LinkedTreeMap single_data = (LinkedTreeMap) data.get(0);
                                            Object step = single_data.get("step");
                                            Object icon = single_data.get("icon");
                                            int num_step = Double.valueOf((Double) step).intValue();
                                            String str_icon = String.valueOf(icon);
                                            System.out.println(num_step);
                                            context.runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    wv.loadUrl("javascript:changeStep(" + (num_step - 2) + ")");
                                                    int resID = getResources().getIdentifier(str_icon, "drawable", context.getPackageName());
                                                    System.out.println(resID);
                                                    Drawable image = getResources().getDrawable(resID);

                                                    carMonView.setImageDrawable(image);
                                                }
                                            });
                                        }
                                    });
                                }
                            }
                        });


            }).run();


//
//                    Random random = new Random();
//                    int i = random.nextInt(19);
//                    // Random Only
//                    i++;
//                    System.out.println("TIMER " + i);
//                    // FIXME 这里需要考虑实际情况传入进来的数字
//                    wv.loadUrl("javascript:changeStep(" + (i - 1) + ")");
//                    String str_name = null;
//                    if (i < 10 && i > 0) {
//                        str_name = "line03_0" + i;
//                    } else {
//                        str_name = "line03_" + i;
//                    }
//
//                    int resID = getResources().getIdentifier(str_name, "drawable", context.getPackageName());
//                    System.out.println(resID);
//                    Drawable image = getResources().getDrawable(resID);
//
//                    carMonView.setImageDrawable(image);
        }

    }
}
